package com.meitianhui.convenitenbuy.module.mine.ui.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.RelativeLayout;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.meitianhui.convenitenbuy.App;
import com.meitianhui.convenitenbuy.Constants;
import com.meitianhui.convenitenbuy.R;
import com.meitianhui.convenitenbuy.base.BaseToolbarActivity;
import com.meitianhui.convenitenbuy.hyphenate.ui.ChatActivity;
import com.meitianhui.convenitenbuy.module.mine.adapter.MessageDispitchAdapter;
import com.meitianhui.convenitenbuy.module.mine.contract.MessageDispitchContract;
import com.meitianhui.convenitenbuy.module.mine.di.DaggerMineComponent;
import com.meitianhui.convenitenbuy.module.mine.di.MineModule;
import com.meitianhui.convenitenbuy.module.mine.model.rxbusBean.ChatMenuEventBean;
import com.meitianhui.convenitenbuy.module.mine.presenter.MessageDispitchPresenter;
import com.meitianhui.convenitenbuy.util.JumpUtil;
import com.meitianhui.convenitenbuy.util.RxBus;
import com.meitianhui.convenitenbuy.util.RxUtils;
import com.meitianhui.convenitenbuy.util.TipUtils;

import java.util.List;

import javax.inject.Inject;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

/**
 * Created by amy on 2017/11/21.
 */

public class MessageDisPitchActivity extends BaseToolbarActivity implements MessageDispitchContract.View, SwipeRefreshLayout.OnRefreshListener {
    private RelativeLayout mRlMsgSysNotify;
    private RelativeLayout mRlMsgService;
    private RelativeLayout mRlMsgGroup;
    private RecyclerView mRlvMsgList;
    private SwipeRefreshLayout mSrlMsgRefresh;
    @Inject
    MessageDispitchPresenter mMessageDispitchPresenter;
    private List<EMConversation> mConversationList;
    private MessageDispitchAdapter mMessageDispitchAdapter;

    @Override
    protected void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        DaggerMineComponent.builder().appComponent(App.getInstance().getAppComponent()).mineModule(new MineModule(this)).build().inject(this);
        isEnable(false);
        initId();
        initRXClick();
        setTbTitle("消息");
        initData();
    }

    private void initData() {
        //获取消息会话列表
        mConversationList = mMessageDispitchPresenter.getConversationList();
        mMessageDispitchAdapter = new MessageDispitchAdapter(mConversationList, this);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        mRlvMsgList.setLayoutManager(layoutManager);
        mRlvMsgList.setAdapter(mMessageDispitchAdapter);
        //设置消息监听
        mMessageDispitchPresenter.addMessageListener();
        //设置item的点击
        mMessageDispitchAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                EMConversation conversation = mConversationList.get(position);
                String userName = conversation.conversationId();
                Intent intent = new Intent(MessageDisPitchActivity.this, ChatActivity.class);
                if (userName.equals(EMClient.getInstance().getCurrentUser()))
                    TipUtils.showToast(MessageDisPitchActivity.this, getResources().getString(R.string.Cant_chat_with_yourself),3);
                else {
                    if (conversation.isGroup()) {

                        if (conversation.getType() == EMConversation.EMConversationType.ChatRoom) {
                            // it's group chat
                            intent.putExtra("chatType",Constants.CHATTYPE_CHATROOM );
                        } else {
                            intent.putExtra("chatType",Constants.CHATTYPE_GROUP);
                        }


                    }else {
                        intent.putExtra("chatType",Constants.CHATTYPE_SINGLE);
                    }

                    intent.putExtra("userId",userName);
                    startActivity(intent);
                }
            }
        });
        //长点击事件
        mMessageDispitchAdapter.setOnItemLongClickListener(new BaseQuickAdapter.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(BaseQuickAdapter adapter, View view, int position) {

                new AlertDialog.Builder(MessageDisPitchActivity.this)
                        .setItems(new String[]{"删除本条记录", "删除本条记录和聊天记录"},
                                new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog,
                                                        int which) {
                                        mMessageDispitchPresenter.remove(mConversationList,position,which,dialog);

                                        mConversationList.clear();
                                        mConversationList.addAll(mMessageDispitchPresenter.getConversationList());
                                        mMessageDispitchAdapter.setNewData(mConversationList);
                                    }
                                }).show();
                return true;
            }
        });

        //当聊天界面有信息跟新时，通知Adapter刷新
        Disposable subscribe = RxBus.get().toFlowable(ChatMenuEventBean.class).subscribe(new Consumer<ChatMenuEventBean>() {
            @Override
            public void accept(ChatMenuEventBean chatMenuEventBean) throws Exception {
                mConversationList.clear();
                mConversationList.addAll(mMessageDispitchPresenter.getConversationList());
                mMessageDispitchAdapter.setNewData(mConversationList);
            }
        });
        mCompositeDisposable.add(subscribe);

        mSrlMsgRefresh.setOnRefreshListener(this);

    }


    @Override
    public void call(View v) {
        super.call(v);
        switch (v.getId()) {
            case R.id.rl_msg_group:
                Intent groupIntent = new Intent(this, MessageGroupActivity.class);
                startActivity(groupIntent);
                break;
            case R.id.rl_msg_service:
                JumpUtil.jumpToChatActivity(this, "bendishenghuoserviceagent");
                break;
            case R.id.rl_msg_sys_notify:
                Intent intent = new Intent(this, SystemNotifyActivity.class);
                startActivity(intent);
                break;
        }
    }

    private void initRXClick() {
        RxUtils.bindEvents(mRlMsgGroup, this);
        RxUtils.bindEvents(mRlMsgService, this);
        RxUtils.bindEvents(mRlMsgSysNotify, this);
    }

    private void initId() {
        mRlMsgSysNotify = getViewById(R.id.rl_msg_sys_notify);
        mRlMsgGroup = getViewById(R.id.rl_msg_group);
        mRlMsgService = getViewById(R.id.rl_msg_service);
        mRlvMsgList = getViewById(R.id.rlv_msg_list);
        mSrlMsgRefresh = getViewById(R.id.srl_msg_refresh);
    }

    @Override
    protected int setView() {
        return R.layout.activity_message_dispitch;
    }

    @Override
    protected void onRefreshData() {

    }

    @Override
    public void showError(String msg) {
        TipUtils.showToast(App.getInstance(), msg);
    }

    /**
     * 监听到有消息改变时，重新拉取数据，重新添加到消息容器中
     */
    @Override
    public void refreshConversation() {
        mConversationList.clear();
        mConversationList.addAll(mMessageDispitchPresenter.getConversationList());
        mMessageDispitchAdapter.setNewData(mConversationList);
    }

    @Override
    public void dismissDialog(DialogInterface dialog) {
        dialog.dismiss();
    }



    /**
     * 下拉刷新
     */
    @Override
    public void onRefresh() {
        mConversationList.clear();
        mConversationList.addAll(mMessageDispitchPresenter.getConversationList());
        mMessageDispitchAdapter.setNewData(mConversationList);
        mSrlMsgRefresh.setRefreshing(false);
    }
}
